#Author:cc
import requests
from bs4 import BeautifulSoup

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr,formataddr

import smtplib

import time

import threading

def getHTML(url):
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ''

def getNEWSINFO(html):
    s = ''
    soup = BeautifulSoup(html,'lxml')
    a = soup.find_all('ul',attrs='ulist focuslistnews')
    for i in a :
        s = s+i.text+'\n'
    return s

def _format_addr(s):
    name,addr = parseaddr(s)
    return formataddr((Header(name,'utf-8').encode(),addr))

def send_msg(s_tr):

    msg = MIMEText(s_tr,'plain','utf-8')

    from_addr = 'cuichen@qkjr.com.cn'
    password = 'Cuichen1993'
    to_addr = 'cuichen@qkjr.com.cn'
    smtp_server = 'smtp.exmail.qq.com'

    msg['From'] = _format_addr('崔晨 <%s>' % from_addr)
    msg['To'] = _format_addr('崔晨 <%s>'% to_addr)
    msg['Subject'] = Header('今日新闻','utf-8').encode()

    server = smtplib.SMTP(smtp_server,'25')
    server.set_debuglevel(1)
    server.login(from_addr,password)
    server.sendmail(from_addr,[to_addr],msg.as_string())
    server.quit()


def main():
    localtime = time.localtime(time.time())
    if localtime[3] == 8:
        url = 'http://news.baidu.com/'
        html = getHTML(url)
        str_news = getNEWSINFO(html)
        send_msg(str_news)

def fun_timer():
    main()
    timer = threading.Timer(86400,fun_timer)
    timer.start()

fun_timer()